package com.vhall.component.service.room.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.room.InvestRefMapper;
import com.vhall.component.dao.room.InvestRefRelationMapper;
import com.vhall.component.entity.room.dto.SelectInvestRefDTO;
import com.vhall.component.entity.room.entity.InvestRefEntity;
import com.vhall.component.entity.room.entity.InvestRefRelationEntity;
import com.vhall.component.entity.room.enums.RefFormEnum;
import com.vhall.component.entity.room.enums.RefRankEnum;
import com.vhall.component.entity.room.enums.RefStatuEnum;
import com.vhall.component.entity.room.enums.RefTypeEnum;
import com.vhall.component.entity.room.vo.AddInvestRefVO;
import com.vhall.component.entity.room.vo.InvestRefRequestVO;
import com.vhall.component.entity.room.vo.InvestRefResponseVO;
import com.vhall.component.entity.room.vo.RoomInvestRefRelationListRequestVO;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.plugin.core.service.GuoXinService;
import com.vhall.component.service.room.InvestRefService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author xing.wang
 * @description 针对表【invest_ref(投资依据表)】的数据库操作Service实现
 * @createDate 2023-08-08 09:53:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InvestRefServiceImpl extends ServiceImpl<InvestRefMapper, InvestRefEntity>
        implements InvestRefService {
    private final GuoXinService guoXinService;
    private final InvestRefMapper investRefMapper;
    private final InvestRefRelationMapper investRefRelationMapper;

    @Override
    public List<InvestRefResponseVO> getGuoXinInvestRefList(InvestRefRequestVO vo) {
        Token token = TokenThreadLocal.getToken();
        SelectInvestRefDTO dto = new SelectInvestRefDTO();
        dto.setNotesid(token.getThirdPartyUserId());
        dto.setOrgCode(token.getOrgCode());
        dto.setBgbt(vo.getInvestRefTitle());
        JSONObject investRefList = Optional.ofNullable(guoXinService.getInvestRefList(dto)).orElse(new JSONObject());
        JSONArray list = investRefList.getJSONArray("list");
        List<InvestRefResponseVO> result = new ArrayList<>();
        if (Objects.nonNull(list)) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                JSONObject investRefInfo = list.getJSONObject(i);
                InvestRefResponseVO data = guoXinService.buildInvestRefInfo(investRefInfo);
                result.add(data);
            }
        }
        return result;
    }

    @Override
    public Boolean addInvestRef(AddInvestRefVO vo) {
        LambdaQueryWrapper<InvestRefEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(InvestRefEntity::getJyId, vo.getJyId());
        InvestRefEntity investRefEntity = investRefMapper.selectOne(queryWrapper);
        if (Objects.isNull(investRefEntity)) {
            investRefEntity = new InvestRefEntity();
            BeanUtil.copyProperties(vo, investRefEntity);
            if (NumberUtil.isNumber(vo.getJyId())) {
                investRefEntity.setId(Integer.parseInt(vo.getJyId()));
            }
            int insert = investRefMapper.insert(investRefEntity);
            if (insert <= 0) {
                throw new BusinessException(BizErrorCode.SAVE_FAIL);
            }

        } else {
            BeanUtil.copyProperties(vo, investRefEntity);
            int updateById = investRefMapper.updateById(investRefEntity);
            if (updateById <= 0) {
                throw new BusinessException(BizErrorCode.SAVE_FAIL);
            }
        }
        return true;
    }

    @Override
    public List<InvestRefResponseVO> getRoomInvestRefRelationList(RoomInvestRefRelationListRequestVO vo) {

        Integer ilId = Optional.ofNullable(vo.getIlId()).orElse(0);
        Integer roomDraftRecordId = Optional.ofNullable(vo.getRoomDraftRecordId()).orElse(0);
        LambdaQueryWrapper<InvestRefRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        if (ilId >= 1) {
            queryWrapper.eq(InvestRefRelationEntity::getIlId,ilId);
        } else if (roomDraftRecordId >= 1) {
            queryWrapper.eq(InvestRefRelationEntity::getRoomDraftRecordId,roomDraftRecordId);
        }
        List<InvestRefRelationEntity> investRefRelationEntities = investRefRelationMapper.selectList(queryWrapper);
        List<Integer> investRefIds = investRefRelationEntities.stream().map(InvestRefRelationEntity::getInvestRefId).distinct().collect(Collectors.toList());

        Token token = TokenThreadLocal.getToken();
        SelectInvestRefDTO dto = new SelectInvestRefDTO();
        dto.setNotesid(token.getThirdPartyUserId());
        dto.setOrgCode(token.getOrgCode());
        List<InvestRefResponseVO> investRefEntities = new ArrayList<>();
        for (Integer investRefId : investRefIds) {
            dto.setJyid(Objects.toString(investRefId));
            try{
                InvestRefResponseVO entity = guoXinService.getInvestRefEntity(dto, investRefId);
                investRefEntities.add(entity);
            }catch (Exception e){
                log.error("远程获取投资依据发生报错",e);
                InvestRefResponseVO entity = new InvestRefResponseVO();
                entity.setJyId(investRefId.toString());
                investRefEntities.add(entity);
            }
        }

        List<InvestRefResponseVO> result = investRefEntities.stream().map(data -> {
            InvestRefResponseVO temp = new InvestRefResponseVO();
            BeanUtil.copyProperties(data, temp);
            temp.setRefStatusName(RefStatuEnum.getNameByValue(temp.getRefStatus()));
            temp.setRefRankName(RefRankEnum.getNameByValue(temp.getRefRank()));
            temp.setRefFormName(RefFormEnum.getNameByValue(temp.getRefForm()));
            temp.setRefTypeName(RefTypeEnum.getNameByValue(temp.getRefType()));
            return temp;
        }).collect(Collectors.toList());
        return Optional.ofNullable(result).orElse(new ArrayList<>());
    }


}




